<!-- 购买会员 -->
<template>
	<view class="buy">
		<view class="bg">
			<image src="https://yzxk.oss-cn-hangzhou.aliyuncs.com/images/mine/vip/bg5.png"></image>
			<view class="content">
				<!-- #ifdef APP-PLUS -->
				<view class="head">
					<u-icon @click="back" name="arrow-left" size="40rpx" color="#5C2510"></u-icon>
					<view class="title">购买会员</view>
					<view class="txt"></view>
				</view>
				<!-- #endif -->
				<view class="spec_list">
					<view :class="['item', item.checked ? 'act' : '']" v-for="(item, index) in vipList" :key="index"
						@click="isSelected(index)">
						<view class="text1">{{ item.vipName }}</view>
						<view class="text2">￥{{ item.discountPrice }}</view>
						<view class="text3">￥{{ item.originalPrice }}</view>
						<!-- 折扣价/ 原价 -->
						<view class="text4">限时{{ item.groupPurchaseDiscount }}折</view>
						<view class="sale" v-if="item.superValueFlag == 1">超值优惠</view>
					</view>
				</view>
			</view>
		</view>

		<view class="notice">可重复购买，自动续期</view>
		<!-- 分割线 -->
		<view class="gray"></view>

		<view class="pd">
			<view class="title">
				<view class="left">
					<image src="https://yzxk.oss-cn-hangzhou.aliyuncs.com/images/mine/vip/img8.png"></image>
					<view>拼单玩法</view>
				</view>
				<view class="right" @click="goInfo">
					<view>详细规则</view>
					<image src="https://yzxk.oss-cn-hangzhou.aliyuncs.com/images/mine/vip/img7.png"></image>
				</view>
			</view>
		</view>

		<view class="buzhou">发起/参与拼单&emsp;>&emsp;邀请好友&emsp;>&emsp;获得额外会员时长</view>

		<!-- 拼单中 -->
		<view class="pding">
			<view class="title">
				<image src="https://yzxk.oss-cn-hangzhou.aliyuncs.com/images/mine/vip/img8.png"></image>
				<view>{{ checkedInfo.vipName }}拼单中</view>
			</view>
			<scroll-view class="items" v-if="spellsList.length" :scroll-top="0" scroll-y="true">
				<Item v-for="(item, index) in spellsList" :key="index" :row="item" @join="addSpell" :isAll="true" />
			</scroll-view>
			<view class="no" v-else>暂无拼单，可发起拼单或通过好友邀请参与</view>
		</view>

		<!-- 我的拼单 -->
		<view class="me">
			<view class="title">
				<image src="https://yzxk.oss-cn-hangzhou.aliyuncs.com/images/mine/vip/img8.png"></image>
				<view>我的拼单</view>
			</view>
			<scroll-view class="items" v-if="mySpellsList.length" :scroll-top="0" scroll-y="true"
				:show-scrollbar="true">
				<Item v-for="(item, index) in mySpellsList" :key="index" :row="item" @join="inviteSpell" :isMy="true" />
			</scroll-view>
			<view class="no" v-else>暂无拼单，可发起拼单或通过好友邀请参与</view>
		</view>

		<!-- 底部按钮 -->
		<Bottom @buyBtn="buy">
			<template #left>
				<view class="price">￥{{ checkedInfo.discountPrice }}</view>
				<view class="type">单独购买</view>
			</template>
			<template #right>
				<view class="price">￥{{ checkedInfo.groupPurchasePrice }}</view>
				<view class="type">发起拼单</view>
			</template>
		</Bottom>

		<!-- 拼单弹出层 -->
		<spellPopup :show="showAdd" :info="popInfo" @addGroup="addSpellGroup" @close="close" />
		<!-- 我的拼单 -->
		<mySpellPopup :show="showInvite" :info="popInfo" @invite="inviteFriend" @close="close" />

		<!-- 支付方式弹窗 -->
		<u-popup :show="showBuy" @close="showBuy = false" mode="bottom" :round="30" :closeable="true">
			<view class="pay">
				<view class="info">
					{{ spellFlag == 0 ? '单独购买' : '发起拼单' }}
					<text>￥{{ spellFlag == 0 ? checkedInfo.discountPrice : checkedInfo.groupPurchasePrice }}</text>
				</view>
				<u-radio-group v-model="payType" @change="groupChange" placement="column" size="40">
					<!-- #ifdef APP-PLUS -->
					<view class="item">
						<view class="left">
							<image src="https://yzxk.oss-cn-hangzhou.aliyuncs.com/images/mine/vip/zfb.png"></image>
							<text>支付宝</text>
						</view>
						<view>
							<u-radio name="alipay" />
						</view>
					</view>
					<!-- #endif -->
					<view class="item m78">
						<view class="left">
							<image src="https://yzxk.oss-cn-hangzhou.aliyuncs.com/images/mine/vip/vx.png"></image>
							<text>微信</text>
						</view>
						<view>
							<u-radio name="wxpay" />
						</view>
					</view>
				</u-radio-group>
				<view class="btn" @click="submit">立即付款</view>
			</view>
		</u-popup>
		<!-- 付款成功 -->
		<u-popup :show="showSuccess" @close="showSuccess = false" mode="center" round="20">
			<view class="success">
				<view>
					<image src="https://yzxk.oss-cn-hangzhou.aliyuncs.com/images/mine/vip/success.png"></image>
				</view>
				<view class="info">购买成功</view>
				<view>会员时长已到账</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		getUserData,
		vipSpecList,
		isSpellsList,
		mySpellsList,
		createOrder,
		aliPay,
		wxPay
	} from '@/apis/apis.js';
	import Header from '@/components/c_header.vue';
	import Bottom from '../../modules/bottom.vue';
	import Item from '../../modules/item.vue';
	import spellPopup from '../../modules/spellPopup.vue';
	import mySpellPopup from '../../modules/mySpellPopup.vue';
	export default {
		components: {
			Header,
			Bottom,
			Item,
			spellPopup,
			mySpellPopup
		},
		data() {
			return {
				vipList: [], // spec
				checkedInfo: {}, // 选中商品
				user: {}, // 用户信息
				showAdd: false, // 加入拼单弹窗
				showInvite: false, // 我的拼单弹窗
				popInfo: {},
				showBuy: false, //支付弹出
				spellFlag: null, // 购买方式
				payType: null, //支付方式
				showSuccess: false, //支付成功
				spells: {
					// 拼单信息
					pageNum: 0,
					pageSize: 10,
					spellProductId: 2
				},
				spellsList: [],
				mySpellsList: [],
				timer: null,
				orderCode: null,
				payMoney: 0,
				id: '',
				shareId: ''
			};
		},
		onLoad(options) {
			console.log(options);
			let name = options.title ? options.title : '';
			this.id = options.id ? options.id : '';
			this.shareId = options.shareId ? options.shareId : '';
			this.init(name);
			this.userData();
		},
		methods: {
			async init(name) {
				this.vipList = [];
				this.checkedInfo = {};
				const res = await vipSpecList();
				// console.log('商品列表',res)
				res.data.forEach((el, idx) => {
					el.checked = false;
				});
				if (name) {
					res.data.forEach((el, idx) => {
						if (el.vipName == name) {
							el.checked = true;
						}
					});
				} else {
					res.data[0].checked = true;
				}
				this.vipList = res.data;
				const idx = this.vipList.findIndex(el => el.checked);
				this.checkedInfo = res.data[idx];
				this.$forceUpdate();
				this.getSpells();
				this.getmySpells();
			},
			// 用户信息 是否会员
			userData() {
				getUserData().then(res => {
					this.user = res.data;
					uni.setStorageSync('USER_DATA', res.data);
				});
			},
			// 所有拼单列表
			async getSpells() {
				this.spells.spellProductId = this.checkedInfo.id;
				// 正在拼单列表
				const res = await isSpellsList(this.spells);
				console.log('正在拼单列表', res);
				res.data.forEach(el => {
					el.surplus = el.targetNumber - el.doneNumber; // 剩余拼单人数
					//手机支付成功后，spellMembers字段不是null，浏览未支付就是null
				});
				// this.spellsList = res.data
				// 过滤已结束的拼单和用户是拼主
				let id = uni.getStorageSync('USER_DATA').memberId;
				this.spellsList = res.data.filter(el => +new Date(el.endTime) > +new Date());
				this.spellsList = this.spellsList.filter(el => el.memberId !== id);
				this.timer = setInterval(() => {
					this.spellsList.forEach(ele => {
						this.$set(ele, 'times', this.$countDownTime(ele.endTime));
					});
				}, 1000);
				// console.log(this.spellsList);
				if (this.shareId) {
					let cell = this.spellsList.filter(el => el.spellId == this.id);
					console.log(cell[0]);
					this.addSpell(cell[0]);
				}
			},
			// 我的拼单列表
			async getmySpells() {
				const res = await mySpellsList();
				console.log('我的拼单列表', res);
				res.data.forEach(el => {
					el.surplus = el.targetNumber - el.doneNumber; // 剩余拼单人数
				});
				this.mySpellsList = res.data;
				this.timer = setInterval(() => {
					this.mySpellsList.forEach((ele, idx) => {
						this.$set(ele, 'times', this.$countDownTime(ele.endTime));
					});
				}, 1000);
			},
			// 处理订单信息
			createOrder() {
				console.log(this.checkedInfo);
				const plat = uni.getSystemInfoSync().platform;
				//spellFlag 0单独 1拼单
				const price = this.spellFlag == 1 ? this.checkedInfo.groupPurchasePrice : this.checkedInfo.discountPrice;
				const data = {
					courseId: this.checkedInfo.id, //业务id
					courseName: this.checkedInfo.vipName, //	会员套餐或系列或课程名称
					isMember: this.user.vipEndDay > 0 ? 1 : 0, //	是否会员（0：非会员1：会员）
					orderSource: plat == 'android' ? 1 : 2, //订单来源 1安卓，2苹果
					orderType: 3, //	订单类型 1=课程系列订单,2=课程订单，3：会员续费订单
					payMoney: price, //	实付金额
					spellFlag: this.spellFlag, //	是否拼单购买（0：否，1：是）
					totalMoney: price, //	订单总金额
					vipnum: this.checkedInfo.saveNum //	充值会员天数
				};
				return data;
			},
			// 底部点击购买
			buy(e) {
				console.log('是否拼单0否,1是', e);
				this.spellFlag = e;
				// 生成订单
				const data = this.createOrder();
				console.log(data);
				this.payMoney = data.payMoney;
				// 生成订单
				createOrder(data).then(res => {
					console.log(res, 111);
					this.orderCode = res.data;
					this.showBuy = true; // 支付方式
				});
				// 选择支付
			},
			//立即付款
			submit() {
				if (!this.payType) {
					uni.showToast({
						title: '请选择支付方式',
						icon: 'none'
					});
					return;
				}
				if (this.payType == 'alipay') {
					let paydata = {
						orderNo: this.orderCode,
						payMoney: this.payMoney.toFixed(2),
						payType: 1, //	支付类型(1：订单支付)
						description: `购买${this.checkedInfo.vipName}`
					};
					console.log('拉取支付宝支付', paydata);
					this.alipayment(paydata);
				} else if (this.payType == 'wxpay') {
					let paydata = {
						orderNo: this.orderCode,
						payMoney: this.payMoney.toFixed(2),
						payType: 1, //	支付类型(1：订单支付)
						description: `购买${this.checkedInfo.vipName}`,
						// #ifdef APP-PLUS
						optType: 2, //	客户端类型(1：小程序, 2:APP )
						// #endif
						// #ifdef MP-WEIXIN
						optType: 1, //	客户端类型(1：小程序, 2:APP )
						// #endif
					};
					console.log('拉取weixin支付', paydata);
					this.wxpayment(paydata);
				}
			},
			// 支付宝
			alipayment(pay) {
				aliPay(pay).then(res => {
					if (res.code == 200) {
						console.log(res, '支付宝参数');
						uni.requestPayment({
							provider: 'alipay',
							orderInfo: res.data,
							success: result => {
								console.log('支付宝支付结果', result);
								// 支付成功
								this.showBuy = false;
								this.showSuccess = true;
								setTimeout(() => {
									this.showSuccess = false;
									this.userData();
									this.init();
									// this.back()
								}, 1500);
							},
							fail: err => {
								console.log('失败', err);
							},
							complete: () => {
								this.showBuy = false;
							}
						});
					} else {
						uni.$u.toast('拉取支付失败');
					}
				});
			},
			// 微信
			wxpayment(pay) {
				wxPay(pay).then(res => {
					if (res.code === 200) {
						// #ifdef APP-PLUS
						uni.requestPayment({
							provider: 'wxpay',
							orderInfo: res.data,
							success: result => {
								console.log('微信支付结果', result);
								// 支付成功
								this.showBuy = false;
								this.showSuccess = true;
								setTimeout(() => {
									this.showSuccess = false;
									this.userData();
									this.init();
								}, 1500);
							},
							fail: err => {
								console.log('失败', err);
							},
							complete: () => {
								this.showBuy = false;
							}
						});
						// #endif
						// #ifdef MP-WEIXIN
						uni.requestPayment({
							provider: 'wxpay',
							orderInfo: pay.description,
							appId: res.data.appId,
							nonceStr: res.data.nonceStr,
							package: res.data.package,
							paySign: res.data.paySign,
							signType: res.data.signType,
							timeStamp: res.data.timeStamp,
							success: result => {
								console.log('微信支付结果', result);
								// 支付成功
								this.showBuy = false;
								this.showSuccess = true;
								setTimeout(() => {
									this.showSuccess = false;
									this.userData();
									this.init();
								}, 1500);
							},
							fail: err => {
								console.log('失败', err);
							},
							complete: () => {
								this.showBuy = false;
							}
						});
						// #endif
						
					} else {
						console.log(res);
						uni.$u.toast('拉取支付失败');
					}
				});
			},
			// 加入拼单
			addSpell(cell) {
				console.log(cell);
				//比较用户memberId和拼主memberId，用户是拼主不能拼单的
				let user = uni.getStorageSync('USER_DATA');
				console.log(user);
				if (user.memberId == cell.memberId) {
					return;
				}
				this.popInfo = cell;
				this.pdType = 2;
				this.showAdd = true;
			},
			addSpellGroup(val) {
				console.log('参与拼单', val);
				this.spellFlag = 1;
				const data = {
					...this.createOrder(),
					spellId: val.spellId
				};
				this.payMoney = data.payMoney;
				createOrder(data).then(res => {
					console.log(res, '创建订单');
					this.orderCode = res.data;
					this.showAdd = false;
					this.showBuy = true; // 选择支付方式
				});
			},
			inviteSpell(cell) {
				console.log(cell);
				this.popInfo = cell;
				this.pdType = 1;
				this.showInvite = true;
			},
			// 邀请好友
			inviteFriend(val) {
				console.log('邀请好友', val);
				uni.navigateTo({
					url: `./pding?id=${val.spellId}`
				});
			},
			//选择支付方式
			groupChange(e) {
				console.log('支付方式', this.payType);
			},
			// 选中商品
			isSelected(v) {
				// console.log(v)
				this.vipList.forEach(el => (el.checked = false));
				this.vipList[v].checked = true;
				this.checkedInfo = this.vipList[v];
				this.getSpells();
				this.$forceUpdate();
			},
			back() {
				uni.navigateBack({
					delta: 1
				});
			},
			// 关闭
			close() {
				this.showAdd = false;
				this.showInvite = false;
			},
			//规则详情
			goInfo() {
				uni.navigateTo({
					url: '/pages/argeement/userArgeement?type=' + 1
				});
			}
		},
		onUnload() {
			this.timer = null;
			clearInterval(this.timer);
		}
	};
</script>

<style lang="scss" scoped>
	.buy {
		padding-bottom: calc(env(safe-area-inset-bottom) + 150rpx);

		.success {
			padding: 42rpx 112rpx 56rpx;
			text-align: center;

			image {
				width: 162rpx;
				height: 160rpx;
			}

			view {
				font-size: 32rpx;
				font-family: Source Han Sans CN;
				font-weight: 500;
				color: #434343;
			}

			.info {
				margin: 28rpx 0 10rpx;
			}
		}

		.pay {
			padding: 68rpx 44rpx 70rpx 34rpx;

			.btn {
				background: #194FC9;
				box-shadow: 0px 12rpx 16rpx 0px rgba(82, 163, 255, 0.3);
				border-radius: 46rpx;
				font-size: 30rpx;
				font-family: PingFangSC;
				font-weight: 400;
				color: #ffffff;
				width: 636rpx;
				height: 90rpx;
				line-height: 90rpx;
				text-align: center;
				margin: 128rpx auto 0;
			}

			.info {
				text-align: center;
				margin-bottom: 112rpx;
				font-size: 28rpx;
				font-family: Source Han Sans CN;
				font-weight: 500;

				text {
					font-size: 40rpx;
					font-family: Adobe Heiti Std;
					font-weight: bold;
					margin-left: 22rpx;
				}
			}

			.m78 {
				margin-top: 78rpx;
			}

			.item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				width: 100%;

				.left {
					display: flex;

					image {
						width: 50rpx;
						height: 50rpx;
						margin-right: 22rpx;
					}
				}
			}
		}

		.bg {
			height: 532rpx;
			position: relative;
			width: 100%;

			&>image {
				width: 100%;
				height: 100%;
				position: absolute;
				pointer-events: none;
				left: 0;
				top: 0;
			}

			.content {
				position: relative;
				z-index: 999;
				padding: calc(var(--status-bar-height) + 30rpx) 30rpx 100rpx;

				.head {
					display: flex;
					justify-content: space-between;
					font-size: 32rpx;
					font-weight: bold;
					color: #5c2510;

					.txt {
						font-size: 28rpx;
						font-weight: normal;
					}
				}
			}

			.spec_list {
				margin-top: 86rpx;
				display: flex;
				justify-content: space-between;
				padding: 0 58rpx;

				.item {
					position: relative;
					width: 240rpx;
					height: 326rpx;
					border-radius: 14rpx;
					border: 3rpx solid #e6e6e6;
					background-color: #fff;
					text-align: center;

					.text1 {
						color: #2a292a;
						font-size: 30rpx;
						margin-top: 50rpx;
					}

					.text2 {
						font-size: 40rpx;
						font-family: Source Han Sans CN;
						font-weight: bold;
						color: #deb762;
						margin-top: 16rpx;
					}

					.text3 {
						font-size: 28rpx;
						font-family: Source Han Sans CN;
						font-weight: 400;
						text-decoration: line-through;
						color: #929292;
					}

					.text4 {
						margin: 32rpx auto 0;
						width: 196rpx;
						height: 56rpx;
						background: linear-gradient(-90deg, #f4deb3, #e8bb68);
						border-radius: 28rpx;
						line-height: 56rpx;
						font-size: 26rpx;
						font-family: Source Han Sans CN;
						font-weight: 500;
						opacity: 0.55;
						color: #ffffff;
					}

					.sale {
						position: absolute;
						left: 0;
						top: -20rpx;
						padding: 6rpx 12rpx;
						background: linear-gradient(-79deg, #fb333b, #fc685a);
						border-radius: 14rpx 0px 14rpx 0px;
						font-size: 26rpx;
						font-family: Source Han Sans CN;
						font-weight: 500;
						color: #ffffff;
					}
				}

				.act {
					background: #fff9f0;
					border: 3rpx solid #deb762;

					.text4 {
						opacity: 1;
						color: #432005;
					}
				}
			}
		}

		.notice {
			margin: 44rpx 0;
			padding-left: 32rpx;
			font-size: 28rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #373737;
		}

		.gray {
			width: 100%;
			height: 16rpx;
			background-color: #f9f9f9;
		}

		.pd {
			padding: 0 30rpx;

			.title {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 34rpx 0;

				.left {
					display: flex;
					justify-content: space-between;
					align-items: center;
					font-size: 32rpx;
					font-family: Source Han Sans CN;
					font-weight: 500;
					color: #1c1c1c;

					image {
						width: 26rpx;
						height: 14rpx;
						margin-right: 10rpx;
					}
				}

				.right {
					display: flex;
					justify-content: space-between;
					align-items: center;
					font-size: 26rpx;
					font-family: Source Han Sans CN;
					font-weight: 400;
					color: #9a9a9a;

					image {
						width: 14rpx;
						height: 24rpx;
						margin-left: 12rpx;
					}
				}
			}
		}

		.buzhou {
			padding: 22rpx 46rpx;
			background-color: rgb(234, 248, 255);
			color: #359bff;
			font-size: 28rpx;
			display: flex;
			justify-content: center;
		}

		.pding,
		.me {
			padding: 0 30rpx;

			.items {
				max-height: 300rpx;
				background: #ffffff;
				box-shadow: 0px 2rpx 20rpx 0px rgba(183, 183, 183, 0.5);
				border-radius: 20rpx;
				margin: 38rpx 0 60rpx;
			}

			.title {
				margin-top: 52rpx;
				display: flex;
				align-items: center;
				font-size: 32rpx;
				font-family: Source Han Sans CN;
				font-weight: 500;
				color: #1c1c1c;

				image {
					width: 26rpx;
					height: 14rpx;
					margin-right: 10rpx;
				}
			}

			.no {
				margin-top: 32rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #999999;
			}
		}

		.me {
			min-height: 280rpx;
		}

		.price {
			font-size: 30rpx;
			font-family: PingFang SC;
			font-weight: bold;
			line-height: 44rpx;
			margin-bottom: 10rpx;
		}

		.type {
			font-size: 26rpx;
			font-family: PingFang SC;
			font-weight: 500;
		}
	}
</style>
